import request from "request-promise";
const baseUrl = "https://api.weixin.qq.com/sns/oauth2/";
const urlConfig = {
  authorize: "https://open.weixin.qq.com/connect/oauth2/authorize?",
  access_token: baseUrl + "access_token?",
  userInfo:"https://api.weixin.qq.com/sns/userinfo?"
};

export default class Oauth {
  constructor(opt) {
    this.appID = opt.appID;
    this.appsecret = opt.appsecret;
  }

  // 请求函数
  async request(options) {
    options = Object.assign({}, options, { json: true });
    try {
      const res = await request(options);
      return res;
    } catch (e) {
      console.error(e);
    }
  }

  async getAuthorizeUrl(url,state,scope="snsapi_base") {
    const reqUrl =`${urlConfig.authorize}appid=${this.appID}&redirect_uri=${encodeURIComponent(url)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
    return reqUrl;
  }

  async fetchAccessToken(code) {
    const url =`${urlConfig.access_token}appid=${this.appID}&secret=${this.appsecret}&code=${code}&grant_type=authorization_code`;
    const token =await this.request({url});
    return token;
  }

  async getUserInfo (token, openID, lang='zh_CN') {
    const url = `${urlConfig.userInfo}access_token=${token}&openid=${openID}&lang=${lang}`
    const data = await this.request({url})
    return data
  }

}
